package lts_service

import (
	"beta/models"
	"beta/pkg/logger"
	"beta/pkg/util"
	"errors"
	"github.com/tidwall/gjson"
	"net/url"
	"time"
)


type LtsService struct {
	Namespace string
	TraceId string
}

func (l LtsService) AddLtsJob(jobName string) error {

	job, jobErr:= models.GetJobByName(jobName, l.Namespace)

	if jobErr != nil {
		return jobErr
	}
	var jobUrl string


	logger.ZapLogger.Infow("查询的job", "结果", job)

	queryString := "taskId=test&jobType=REAL_TIME_JOB&cronExpression=" +
		"&triggerTime=&repeatInterval=&repeatCount=&relyOnPrevCycle=" +
		"&needFeedback=false&priority=100&maxRetryTimes=0&submitNodeGroup="

	extParams := url.QueryEscape("{\"jobClassName\":\""+ job.Classname + "\"}")

	queryString += "&taskTrackerNodeGroup=" + job.JobGroup + "&extParams=" + extParams

	var token string
	if l.Namespace == "test" {
		jobUrl = job.JobHost + "/api/job-queue/job-add"
		token = "1248703DA0295EB30E34C35C084D80DAD539F6E0CFFFD184ACE7543BCB23FD461682A8889B7A810AA92C334F2046B563"
	}

	if l.Namespace == "release"  {
		jobUrl = job.JobHost + "/api/job-queue/job-add"
		token = "1248703DA0295EB30E34C35C084D80DAD539F6E0CFFFD184ACE7543BCB23FD461682A8889B7A810AA92C334F2046B563"
	}
	cookie := util.GetCookie(util.BossCookieName, token)
	httpClient := util.NewHttpClientWithCookie(3 * time.Second, cookie)

	resp, respErr := httpClient.R().
		SetQueryString(queryString).
		Post(jobUrl)

	logger.ZapLogger.Infow("【触发lts任务】", "请求参数", job, "请求结果", resp, "错误信息", respErr, "traceId", l.TraceId)
	if respErr != nil {
		return respErr
	}
	if gjson.Get(resp.String(), "msg").String() != "Add success" {
		return  errors.New("添加任务失败")
	}

	return nil

}
